package utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Run this at the very beginning. Generate Keys and write to files.
 * 
 * @author bh349
 * 
 */
public class KeyGen
{
    /**
     * @param args
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static void main( String[] args ) throws IOException,
            NoSuchAlgorithmException {
        KeyPairGenerator gen = KeyPairGenerator.getInstance( "RSA" );
        gen.initialize( 3072 );
        KeyPair keyPair = gen.generateKeyPair();
        writePublicKeytoFile( keyPair.getPublic(), "Alice" );
        writePrivateKeyToFile( keyPair.getPrivate(), "Alice" );
        keyPair = gen.generateKeyPair();
        writePublicKeytoFile( keyPair.getPublic(), "Bob" );
        writePrivateKeyToFile( keyPair.getPrivate(), "Bob" );
    }

    private static void writePrivateKeyToFile( PrivateKey sk, String clientName )
            throws IOException {
        if( "Alice".equals( clientName ) )
            writeBytesToFile( sk.getEncoded(),
                    ConstantVariables.ALICE_PRIVATEKEY );
        else
            writeBytesToFile( sk.getEncoded(), ConstantVariables.BOB_PRIVATEKEY );
    }

    private static void writePublicKeytoFile( PublicKey pk, String clientName )
            throws IOException {
        if( "Alice".equals( clientName ) )
            writeBytesToFile( pk.getEncoded(),
                    ConstantVariables.ALICE_PUBLICKEY );
        else
            writeBytesToFile( pk.getEncoded(), ConstantVariables.BOB_PUBLICKEY );
    }

    private static void writeBytesToFile( byte[] bytes, String fileName )
            throws IOException {
        File file = new File( fileName );
        FileOutputStream fos = new FileOutputStream( file );
        fos.write( bytes );
        fos.close();
    }
}
